package xyz.iguilty.workflow.core.listener;


import org.flowable.common.engine.api.delegate.event.FlowableEngineEntityEvent;
import org.flowable.engine.RepositoryService;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.TaskService;
import org.flowable.engine.delegate.event.AbstractFlowableEngineEventListener;
import org.flowable.task.service.impl.persistence.entity.TaskEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import xyz.iguilty.workflow.constant.ProcessConstants;
import xyz.iguilty.workflow.core.service.AbstractActivity;
import xyz.iguilty.workflow.model.ActivityContext;
import xyz.iguilty.workflow.model.ActorModel;
import xyz.iguilty.workflow.model.SimpleGroup;
import xyz.iguilty.workflow.model.SimpleUser;
import xyz.iguilty.workflow.utils.ApplicationContextProvider;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringJoiner;

@Component
public class GlobalTaskCompeleteListener extends AbstractFlowableEngineEventListener {

    @Autowired
    private TaskService taskService;

    @Override
    protected void taskCompleted(FlowableEngineEntityEvent event) {
        super.taskCreated(event);
        Object entity = event.getEntity();
        //是否是任务实体类
        if (!(entity instanceof TaskEntity)) {
            return;
        }
        TaskEntity taskEntity = (TaskEntity) entity;
        String taskId = taskEntity.getId();
        AbstractActivity activity = ApplicationContextProvider.getBean(taskEntity.getTaskDefinitionKey(), AbstractActivity.class);
        if (activity == null) {
            return;
        }
        Map<String, Object> variables = new HashMap<>();
        //设置业务当前状态
        String statusAfterCreated = activity.getStatusAfterCompleted();
        variables.put(ProcessConstants.CURRENT_STATUS,statusAfterCreated);
        taskService.setVariables(taskId,variables);
    }

}
